<?php

namespace app\admin\controller\api;

use app\admin\service\WxWorkOAuthService;
use app\admin\service\WxWorkService;
use EasyWeChat\Factory;
use think\admin\Controller;
use think\admin\service\AdminService;
use think\facade\Log;

/**
 * 企业微信回调管理
 * Class WXWork
 * @package app\admin\controller\api
 */
class WxWork extends Controller
{
    /**
     * 回调地址: admin/api.WxWork/contactCallback
     * @return void
     * @throws \EasyWeChat\Kernel\Exceptions\BadRequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \ReflectionException
     */
    public function contactCallback()
    {
        $config = config('office_work');
        $config = [
            'corp_id' => $config['corp_id'],
            'agent_id'   => $config['agent_id'],
            'secret'   => $config['agent_secret'],
            'token' => $config['contact_token'],
            'aes_key' => $config['contact_encoding_aes_key'],
            'response_type' => 'array'
        ];

        $app = Factory::work($config);

        $app->server->push(function($message){
//            {"ToUserName":"wwd112f8b99c1706c0","FromUserName":"sys","CreateTime":"1686036877","MsgType":"event","Event":"change_contact","ChangeType":"update_user","UserID":"jypony","Department":"3,1,2"}
            Log::info('通讯录回调: ' . json_encode($message));
            switch ($message['Event']){
                // 通讯录回调事件
                case 'change_contact' :
                    // 部门事件
                    if (in_array($message['ChangeType'], ['create_party', 'update_party'])){
                        WxWorkService::instance()->departmentList();
                        WxWorkService::instance()->getUserDetailedDepartmentUsers();
                    }
                    if ($message['ChangeType'] == 'delete_party') {
                        WxWorkService::instance()->deleteDepartment($message['Id']);
                    }

                    // 成员事件
                    if (in_array($message['ChangeType'], ['create_user', 'update_user'])){
                        WxWorkService::instance()->getUserInfo($message['UserID']);
                    }
                    if ($message['ChangeType'] == 'delete_user') {
                        WxWorkService::instance()->deleteUser($message['UserID']);
                    }
                    break;
            }
            return 'Hello.';
        });

        $response = $app->server->serve();

        $response->send();
    }

    /**
     * 授权登录回调
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Overtrue\Socialite\Exceptions\AuthorizeFailedException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function oauthCallback()
    {
        $userid = WxWorkOAuthService::instance()->getUserid();

        $user = $this->app->db->name('WorkUser')->where('userid', $userid)->order('id desc')->find();
        if (empty($user)) {
            $this->error('查无该员工!');
        }
        $db = $this->app->db->name('SystemAuth')->field('id')->where(['status' => 1])->whereIn('id', str2arr($user['authorize']));
        $user['nodes'] = array_unique($this->app->db->name('SystemAuthNode')->whereRaw("auth in {$db->buildSql()}")->column('node'));
        $this->app->session->set('user', $user);
        $this->app->db->name('WorkUser')->where(['id' => $user['id']])->update([
            'login_ip'  => $this->app->request->ip(),
            'login_at'  => $this->app->db->raw('now()'),
            'login_num' => $this->app->db->raw('login_num+1'),
        ]);
        sysoplog('企业微信用户登录', '登录系统后台成功');

        $callback = urldecode($this->request->get('callback'));

        header("Location: {$callback}");
    }
}